package com.dq.service.sys.user.impl;

import com.dq.exception.customException.AdminException;

import com.dq.domain.orders.UserOrder;
import com.dq.domain.org.OrgCustomerLevel;
import com.dq.domain.sys.section.SysSection;
import com.dq.domain.sys.user.user.WxUser;
import com.dq.repository.BaseRepositories;
import com.dq.repository.order.UserOrderRepository;
import com.dq.repository.user.OrgCustomerLevelRepository;
import com.dq.repository.user.WxUserRepository;
import com.dq.service.sys.user.WxUserLevelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * @Author luchangtong
 * @Date 2019/12/16 16:23
 */
@Service
public class WxUserLevelServiceImpl extends BaseRepositories implements WxUserLevelService {
    @Autowired
    private UserOrderRepository userOrderRepository;
    @Autowired
    private OrgCustomerLevelRepository orgCustomerLevelRepository;
    @Autowired
    private WxUserRepository wxUserRepository;
    @Override
    public void checkLevel(UserOrder userOrder) throws AdminException {
        WxUser wxUser = dao.get(WxUser.class,userOrder.getWxUser().getId());
        if(wxUser == null){
            throw new AdminException("此会员不存在");
        }
        SysSection org = wxUser.getSection();
        if(org == null){
            throw new AdminException("请先绑定门店");
        }
        BigDecimal sum = userOrderRepository.countByWxUser(wxUser, UserOrder.UserOrderStatus.alreadyCheckOut).add(userOrder.getPrice());
        OrgCustomerLevel orgCustomerLevel = orgCustomerLevelRepository.findByMinAmountLessThanEqualAndMaxAmountGreaterThanEqualAndDeletedFalse(sum,sum);
        if(orgCustomerLevel == null){
            throw new AdminException("请设置好等级的消费区间");
        }
        wxUser.setMemberType(WxUser.MemberType.formal);
        wxUser.setOrgCustomerLevel(orgCustomerLevel);
        wxUserRepository.save(wxUser);
    }
}
